/**
 * 
 */
package com.playball.lottery.frm.buyhall;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.graphics.Point;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.playball.lottery.R;
import com.playball.lottery.base.BaseActivity;
import com.playball.lottery.customview.draglistview.DragSortController;
import com.playball.lottery.customview.draglistview.DragSortListView;
import com.playball.lottery.util.LotUtil;
import com.playball.lottery.util.cache.MyPreference;


/**
 * @author sunfanglei
 * @date 2014年4月9日
 */
public class AddMoreLotsActivity extends BaseActivity {

	private List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
	private List<Map<String, Object>> navList = new ArrayList<Map<String, Object>>();
	private List<Map<String, Object>> moreList = new ArrayList<Map<String, Object>>();
	private DragSortListView dragListView;
	SectionAdapter adapter = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.addmorelot);
		dragListView = (DragSortListView) findViewById(R.id.dragSortListView1);
		navList = MyPreference.getStringArrayPreflist2(this, "MH", "deflot");
		moreList = MyPreference.getStringArrayPreflist2(this, "MH", "restlot");
		dataList.addAll(navList);
		dataList.addAll(moreList);
		adapter = new SectionAdapter(this, dataList, navList.size());
		dragListView.setDropListener(adapter);

		// make and set controller on dslv
		SectionController c = new SectionController(dragListView, adapter);
		dragListView.setFloatViewManager(c);
		dragListView.setOnTouchListener(c);
		// pass it to the ListActivity
		dragListView.setAdapter(adapter);

		// TextView addmore_btn_ok = (TextView)
		// findViewById(R.id.addmore_btn_ok);
		// addmore_btn_ok.setOnClickListener(new OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		// int pos = adapter.getDivPosition();
		// List<Map<String, Object>> list = adapter.getData();
		// List<Map<String, Object>> list1 = list.subList(0, pos);
		// List<Map<String, Object>> list2 = list.subList(pos, list.size());
		// MyPreference.setStringArrayPreflist2(AddMoreLotsActivity.this, "MH",
		// "deflot", list1);
		// MyPreference.setStringArrayPreflist2(AddMoreLotsActivity.this, "MH",
		// "restlot", list2);
		// setResult(RESULT_OK);
		// finish();
		// }
		// });

		ImageView top_title_back_bg = (ImageView) findViewById(R.id.top_title_back_bg);
		top_title_back_bg.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						int pos = adapter.getDivPosition();
						List<Map<String, Object>> list = adapter.getData();
						List<Map<String, Object>> list1 = list.subList(0, pos);
						List<Map<String, Object>> list2 = list.subList(pos, list.size());
						MyPreference.setStringArrayPreflist2(AddMoreLotsActivity.this, "MH", "deflot", list1);
						MyPreference.setStringArrayPreflist2(AddMoreLotsActivity.this, "MH", "restlot", list2);
						setResult(RESULT_OK);
						finish();
					}
				});
			}
		});

	}

	public void onResume() {
		super.onResume();
		
	}

	public void onPause() {
		super.onPause();
		
	}

	private class SectionController extends DragSortController {

		private int mPos;
		private int mDivPos;

		private SectionAdapter mAdapter;

		DragSortListView mDslv;

		public SectionController(DragSortListView dslv, SectionAdapter adapter) {
			super(dslv, R.id.mh_iv_lot_icon, DragSortController.ON_DOWN, 0);
			setRemoveEnabled(false);
			mDslv = dslv;
			mAdapter = adapter;
			mDivPos = adapter.getDivPosition();
		}

		@Override
		public int startDragPosition(MotionEvent ev) {
			mDivPos = mAdapter.getDivPosition();
			int res = super.dragHandleHitPosition(ev);
			if (res == mDivPos) {
				return DragSortController.MISS;
			}

			int width = mDslv.getWidth();

			if ((int) ev.getX() < width / 3) {
				return res;
			} else {
				return DragSortController.MISS;
			}
		}

		@Override
		public View onCreateFloatView(int position) {
			mPos = position;

			View v = mAdapter.getView(position, null, mDslv);
			// if (position < mDivPos) {
			// v.setBackgroundDrawable(getResources().getDrawable(R.drawable.icon_notice));
			// } else {
			// v.setBackgroundDrawable(getResources().getDrawable(R.drawable.icon_notice));
			// }
			// v.getBackground().setLevel(10000);
			return v;
		}

		private int origHeight = -1;

		@Override
		public void onDragFloatView(View floatView, Point floatPoint, Point touchPoint) {
			final int first = mDslv.getFirstVisiblePosition();
			final int lvDivHeight = mDslv.getDividerHeight();

			if (origHeight == -1) {
				origHeight = floatView.getHeight();
			}

			View div = mDslv.getChildAt(mDivPos - first);

			if (touchPoint.x > mDslv.getWidth() / 2) {
				float scale = touchPoint.x - mDslv.getWidth() / 2;
				scale /= (float) (mDslv.getWidth() / 5);
				ViewGroup.LayoutParams lp = floatView.getLayoutParams();
				lp.height = Math.max(origHeight, (int) (scale * origHeight));
				floatView.setLayoutParams(lp);
			}

			if (div != null) {
				if (mPos > mDivPos) {
					// don't allow floating View to go above
					// section divider
					final int limit = div.getBottom() + lvDivHeight;
					if (floatPoint.y < limit) {
						floatPoint.y = limit;
					}
				} else {
					// don't allow floating View to go below
					// section divider
					final int limit = div.getTop() - lvDivHeight - floatView.getHeight();
					if (floatPoint.y > limit) {
						floatPoint.y = limit;
					}
				}
			}
		}

		@Override
		public void onDestroyFloatView(View floatView) {
			// do nothing; block super from crashing
		}

	}

	private class SectionAdapter extends BaseAdapter implements DragSortListView.DropListener {

		private final static int SECTION_DIV = 0;
		private final static int SECTION_ONE = 1;
		private final static int SECTION_TWO = 2;

		private List<Map<String, Object>> mData;

		private int mDivPos;

		private LayoutInflater mInflater;

		private Context context;

		public SectionAdapter(Context context, List<Map<String, Object>> names, int mDivPos) {
			super();
			this.context = context;
			mInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
			mData = names;
			this.mDivPos = mDivPos;
		}

		@Override
		public void drop(int from, int to) {
			if (from != to) {
				Map<String, Object> data = mData.remove(dataPosition(from));
				mData.add(dataPosition(to), data);
				notifyDataSetChanged();
			}
		}

		public List<Map<String, Object>> getData() {
			return mData;
		}

		@Override
		public int getCount() {
			return mData.size() + 1;
		}

		@Override
		public boolean areAllItemsEnabled() {
			return false;
		}

		@Override
		public boolean isEnabled(int position) {
			return position != mDivPos;
		}

		public int getDivPosition() {
			return mDivPos;
		}

		@Override
		public int getViewTypeCount() {
			return 3;
		}

		@Override
		public Map<String, Object> getItem(int position) {
			if (position == mDivPos) {
				return null;
			} else {
				return mData.get(dataPosition(position));
			}
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public int getItemViewType(int position) {
			if (position == mDivPos) {
				return SECTION_DIV;
			} else if (position < mDivPos) {
				return SECTION_ONE;
			} else {
				return SECTION_TWO;
			}
		}

		private int dataPosition(int position) {
			return position > mDivPos ? position - 1 : position;
		}

		// public Drawable getBGDrawable(int type) {
		// Drawable d;
		// if (type == SECTION_ONE) {
		// d = getResources().getDrawable(R.drawable.icon_notice);
		// } else {
		// d = getResources().getDrawable(R.drawable.icon_notice);
		// }
		// d.setLevel(3000);
		// return d;
		// }

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			final int type = getItemViewType(position);

			if (convertView != null) {
			} else if (type != SECTION_DIV) {
				convertView = mInflater.inflate(R.layout.mh_lot_item, parent, false);
			} else {
				convertView = mInflater.inflate(R.layout.drag_list_item_tag, parent, false);
			}
			if (type != SECTION_DIV) {
				// bind data
				ImageView iv = (ImageView) convertView.findViewById(R.id.mh_iv_lot_icon);
				TextView tv_lot_name = (TextView) convertView.findViewById(R.id.mh_tv_lot_name);
				TextView tv_lot_info = (TextView) convertView.findViewById(R.id.mh_tv_lot_info);
				TextView tv_lot_action = (TextView) convertView.findViewById(R.id.mh_tv_lot_action);
				Map<String, Object> item = mData.get(dataPosition(position));
				iv.setBackgroundResource(LotUtil.getIconByID(Integer.parseInt(item.get("LotID").toString())));
				tv_lot_name.setText(LotUtil.getLotNamebyID(Integer.parseInt(item.get("LotID").toString())));
				String lotinfo = item.get("LotInfo").toString();
				if (lotinfo.isEmpty()) {
					tv_lot_action.setVisibility(View.INVISIBLE);
				} else {
					tv_lot_action.setText(lotinfo);
				}
				tv_lot_info.setText(LotUtil.getLotDesByID(Integer.parseInt(item.get("LotID").toString())));
				ImageView imageView = (ImageView) convertView.findViewById(R.id.mh_iv_right_icon);
				if (type == SECTION_ONE) {
					imageView.setBackgroundResource(R.drawable.mh_btn_minus_bg);
					imageView.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							if (mDivPos <= 4) {
								runOnUiThread(new Runnable() {
									public void run() {
										Toast.makeText(context, R.string.at_least_four_colour_should_be_preserved,
												Toast.LENGTH_SHORT).show();
									}
								});
							} else {
								Map<String, Object> data = mData.remove(dataPosition(position));
								mData.add(data);
								mDivPos = mDivPos - 1;
								notifyDataSetChanged();
							}
						}
					});
				} else {
					imageView.setBackgroundResource(R.drawable.mh_btn_add_bg);
					imageView.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							Map<String, Object> data = mData.remove(dataPosition(position));
							mData.add(mDivPos, data);
							mDivPos = mDivPos + 1;
							notifyDataSetChanged();
						}
					});
				}
			}

			return convertView;
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					int pos = adapter.getDivPosition();
					List<Map<String, Object>> list = adapter.getData();
					List<Map<String, Object>> list1 = list.subList(0, pos);
					List<Map<String, Object>> list2 = list.subList(pos, list.size());
					MyPreference.setStringArrayPreflist2(AddMoreLotsActivity.this, "MH", "deflot", list1);
					MyPreference.setStringArrayPreflist2(AddMoreLotsActivity.this, "MH", "restlot", list2);
					setResult(RESULT_OK);
					finish();
				}
			});
		}
		return true;
	};
}
